use axum::Json;
use serde_json::{Value, json};
use crate::{reqwest, query, code };
use super::access_token;

// 获取客服列表
pub async fn list() -> Result<Json<Value>, Json<Value>>{
    let access_token = access_token::token().await?;
    let offset = 0;
    let limit = 0;
    let url = format!(
        "https://qyapi.weixin.qq.com/cgi-bin/kf/account/add?access_token={}&offset={}&limit={}",
        access_token, 
        offset,         // 
        limit           //
    );
    let rs = reqwest::post(&url,json!({})).await?;
    if let Some( f ) = query::vec_op(&rs, "account_list")? {
        code::data(json!(f))
    }else {
        Err(code::err_("添加客服失败"))
    }
}
// 添加客服账号
pub async fn add(name:&str, media_id:&str) -> Result<Json<Value>, Json<Value>>{
    let access_token = access_token::token().await?;
    let url = format!(
        "https://qyapi.weixin.qq.com/cgi-bin/kf/account/add?access_token={}&name={}&media_id={}",
        access_token, 
        name,           // 客服账号名称,不多于 16 个字符 
        media_id        // 客服头像临时素材。可以调用上传临时素材接口获取
    );
    let rs = reqwest::post(&url,json!({})).await?;
    if let Some( _f ) = query::str_op(&rs, "open_kfid")? {
        code::ok()
    }else {
        code::err("添加客服失败")
    }
}
// 删除客服账号
pub async fn del(open_kfid:&str) -> Result<Json<Value>, Json<Value>>{
    let access_token = access_token::token().await?;
    let url = format!(
        "https://qyapi.weixin.qq.com/cgi-bin/kf/account/del?access_token={}&open_kfid={}",
        access_token, 
        open_kfid,           // 客服账号 ID。不多于64字节
    );
    let rs = reqwest::post(&url,json!({})).await?;
    if query::i64(&rs, "errcode")?.eq(&0) {
        code::ok()
    }else {
        code::err("删除客服失败")
    }
}
// 修改客服账号
pub async fn update(open_kfid:&str, name:&str, media_id:&str) -> Result<Json<Value>, Json<Value>>{
    let access_token = access_token::token().await?;
    let url = format!(
        "https://qyapi.weixin.qq.com/cgi-bin/kf/account/update?access_token={}&open_kfid={}&name={}&media_id={}",
        access_token, 
        open_kfid,           // 客服账号 ID。不多于64字节
        name,                // 新的客服账号名称，如不需要修改可不填。不多于16个字符
        media_id             // 新的客服头像临时素材 
    );
    let rs = reqwest::post(&url,json!({})).await?;
    if query::i64(&rs, "errcode")?.eq(&0) {
        code::ok()
    }else {
        code::err("修改客服失败")
    }
}
// 获取客服链接 url
pub async fn url( open_kfid:&str, scene:&str ) -> Result<String, Json<Value>>{
    let access_token = access_token::token().await?;
    let url = format!(
        "https://qyapi.weixin.qq.com/cgi-bin/kf/add_contact_way?access_token={}&open_kfid={}&scene={}",
        access_token, open_kfid, scene
    );
    let rs = reqwest::post(&url,json!({})).await?;
    if let Some( url ) = query::str_op(&rs, "url")? {
        Ok( url )
    }else {
        Err(code::err_("获取客服链接失败"))
    }
}